<template>
  <div class="card-box">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="fromRules"
      label-width="140px"
      class="form__content"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label-width="120px" label="单据名称" prop="billName">
            <el-input v-model="formData.billName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="120px" label="项目名称" prop="projectName">
            <el-select
              v-model="currentProject.projectName"
              clearable
              placeholder="请选择"
            >
              <el-option :value="projectList">
                <el-tree
                  id="tree-option"
                  :data="projectList"
                  accordion
                  node-key="id"
                  ref="projectTreeRef"
                  highlight-current
                  :props="defaultProps"
                  @check-change="handleCheckChange"
                  check-on-click-node
                  :expand-on-click-node="false"
                >
                </el-tree>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="120px" label="合同名称" prop="contractId">
            <el-select
              v-model="formData.contractId"
              ref="contractRef"
              @change="handleChangeContract"
            >
              <!-- value-key="contractId" -->
              <el-option
                id="default-option"
                v-for="item in contracList"
                :key="item.contractId"
                :label="item.contractName"
                :value="item.contractId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="120px" label="合同编号" prop="contractNum">
            <el-input v-model="formData.contractNum" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label-width="120px" label="甲方单位名称" prop="partyA">
            <el-input v-model="formData.partyA" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label-width="120px"
            label="甲方负责人"
            prop="directorAName"
          >
            <el-input v-model="formData.directorAName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="120px" label="乙方单位名称" prop="partyB">
            <el-input v-model="formData.partyB" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label-width="120px"
            label="乙方负责人"
            prop="directorBName"
          >
            <el-input v-model="formData.directorBName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label-width="120px"
            label="隐蔽自检记录"
            prop="selfCheckRecord"
          >
            <el-input
              type="textarea"
              :row="3"
              v-model="formData.selfCheckRecord"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label-width="140px"
            label="附件上传"
            prop="flowStartAttachmentArr"
          >
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :accept="acceptTypes"
              name="uploadFile"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :on-error="handleError"
              :on-preview="handlePreview"
              multiple
              :file-list="defaultFileList"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传doc、docx、xls、xlsx、pdf、png、jpg、jpeg等格式文件,文件大小不得大于20M。
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label-width="120px" label="备注" prop="remarks">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="formData.remarks"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form__footer">
      <el-button type="primary" @click="handleSave">保 存</el-button>
      <el-button type="primary" @click="handleSubmit">提 交</el-button>
    </div>
    <el-dialog
      title="提交"
      v-model="commitVisible"
      destroy-on-close
      width="600px"
    >
      <div class="dialog__content">
        <div class="dialog__content--title">提交信息:</div>
        <el-row>
          <el-col :span="3" class="col-left"></el-col>
          <el-col :span="21" class="col-right"
            >项目名称：{{ formData.projectName }}</el-col
          >
        </el-row>
        <el-row>
          <el-col :span="3" class="col-left"></el-col>
          <el-col :span="21" class="col-right"
            >合同名称：{{ formData.contractName }}</el-col
          >
        </el-row>
        <el-row>
          <el-col :span="3" class="col-left"></el-col>
          <el-col :span="21" class="col-right"
            >合同编号：{{ formData.contractNum }}</el-col
          >
        </el-row>
        <el-row>
          <el-col :span="3" class="col-left"></el-col>
          <el-col :span="21" class="col-right"
            >下一流程处理人：{{ currentTeam.userName }}</el-col
          >
        </el-row>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commitVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click="handleRequest">确认</el-button> -->
          <ReButton type="primary" debounce auto-loading @click="handleRequest"
            >确认</ReButton
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, watch, unref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { hasRoleCode } from "/@/utils/hasRoleCode";
import {
  postComFlowStart,
  postFlowSave,
  postProjectTree,
  postGetContractList,
  getContractDetail,
  getProTeamMembers
} from "/@/api/acceptance";

import NotifMessage from "/@/utils/message/notification";
import { fieldEncode } from "/@/utils/format/fieldSignFormat";
import { storageLocal } from "/@/utils/storage";

import { acceptTypes, uploadUrl } from "../../types";
import {
  // uploadHeaders,
  handlePreview,
  handleError,
  beforeAvatarUpload
} from "../../utils";

import ReButton from "/@/components/ReButton/index.vue";

const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

const router = useRouter();
const route = useRoute();
let commitVisible = ref<boolean>(false);
const formRef = ref<HTMLFormElement | null>(null) as any;
const contractRef = ref<HTMLElement | null>(null) as any;
const projectTreeRef = ref<HTMLElement | null>(null) as any;
let projectList = ref([]);
let contracList = ref([]);
let currentProject = reactive({
  projectName: "",
  projectManageId: ""
});

let projectTeam = ref([]); // 合同处理人信息
let currentTeam = reactive({
  userName: "",
  userId: ""
}); // 下一节点的处理人信息
const props = defineProps({
  storageData: {
    type: Object,
    default: () => {}
  },
  test: {
    type: String,
    default: ""
  }
});

// const disabledDate = time => {
//   return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
// };

let formData = reactive({
  billName: "",
  projectName: "",
  projectManageId: "",
  contractName: null,
  contractId: null,
  contractNum: "",
  partyA: "",
  directorAName: "",
  directorA: "",
  directorBId: "",
  partyB: "",
  directorBName: "",
  remarks: "",
  selfCheckRecord: "",
  flowStartAttachmentArr: []
});

const fromRules = {
  billName: [{ required: true, message: "请输入单据名称", trigger: "change" }],
  // billNum: "",
  projectName: [
    { required: true, message: "请输入项目名称", trigger: "change" }
  ],
  contractId: [{ required: true, message: "请选择合同", trigger: "change" }],
  selfCheckRecord: [
    { required: true, message: "请填写隐蔽验收记录", trigger: "change" }
  ],
  flowStartAttachmentArr: [
    { required: true, message: "请上传附件", trigger: "change" }
  ]
};

const defaultProps = {
  children: "children",
  label: "projectName",
  id: "id"
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectTree({});
    if (code === 200) {
      projectList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 获取合同信息
const getContractList = async () => {
  try {
    const params = {
      projectPathLike: currentProject.projectManageId
    };
    const { code, data } = await postGetContractList(params);
    if (code === 200) {
      contracList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleCheckChange = () => {
  const res = projectTreeRef.value.getCurrentNode();
  currentProject.projectName = [res][0].projectName;
  currentProject.projectManageId = [res][0].id;
  handleClearFormData();
};

const handleClearFormData = () => {
  formData.contractNum = "";
  formData.partyA = "";
  formData.directorAName = "";
  formData.partyB = "";
  formData.directorBName = "";
  formData.projectManageId = "";
  formData.directorA = "";
  formData.directorBId = "";
  formData.contractId = "";
};

// const initCurrentNode = id => {
//   nextTick(() => {
//     projectTreeRef.value.setCheckedKeys([id], true);
//     projectTreeRef.value.setChecked(id, true, false);
//   });
// };

const handleChangeContract = async () => {
  if (formData.contractId) {
    const params = {
      id: formData.contractId
    };
    const { code, data } = await getContractDetail(params);
    if (code === 200 && data) {
      const {
        contractNum,
        partyA,
        directorAName,
        partyB,
        directorBName,
        projectManageId,
        projectName,
        directorA,
        directorBId,
        contractName
      } = data;
      // console.log(data, "data");
      formData.contractNum = contractNum;
      formData.contractName = contractName;
      formData.partyA = partyA;
      formData.directorAName = directorAName;
      formData.partyB = partyB;
      formData.directorBName = directorBName;
      formData.directorA = directorA;
      formData.directorBId = directorBId;
      formData.projectManageId = projectManageId;
      formData.projectName = projectName;
      currentProject.projectName = formData.projectName;
      currentProject.projectManageId = formData.projectManageId;
    }
  } else {
    handleClearFormData();
  }
};

watch(
  () => props.storageData,
  newVal => {
    setTimeout(() => {
      if (newVal.billName) {
        formData.billName = newVal.billName;
        formData.projectName = newVal.projectName;
        formData.projectManageId = newVal.projectManageId;
        formData.contractName = newVal.contractName;
        formData.contractId = newVal.contractId;
        formData.contractNum = newVal.contractNum;
        formData.partyA = newVal.partyA;
        formData.directorAName = newVal.directorAName;
        formData.partyB = newVal.partyB;
        formData.directorBName = newVal.directorBName;
        formData.remarks = newVal.remarks;
        formData.selfCheckRecord = newVal.selfCheckRecord;
        formData.directorA = newVal.directorA;
        formData.directorBId = newVal.directorBId;
        formData.flowStartAttachmentArr = newVal.flowStartAttachmentArr;
        defaultFileList.value = onInitFileList(formData.flowStartAttachmentArr);
        currentProject.projectName = formData.projectName;
        currentProject.projectManageId = formData.projectManageId;
      }
    }, 500);
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => currentProject,
  newVal => {
    if (newVal) {
      formData.projectName = newVal.projectName;
      getContractList();
    }
  },
  {
    deep: true
  }
);

// 文件上传相关
let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
};

const handleChange = (file, fileList) => {
  defaultFileList.value = fileList;
  formRef.value.clearValidate();
};

const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => item?.response?.data).filter(Boolean);
  return newFileData;
};

const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

const handleSubmit = async () => {
  // formData.billName = `${formData.projectName}-${formData.contractName}-有监理隐蔽验收`;
  formData.flowStartAttachmentArr = onFilterFileData(defaultFileList.value);
  try {
    const isValid = await new Promise(resolve =>
      formRef.value.validate(resolve)
    );
    if (!isValid) return;

    // 获取项目组成员
    await getTeamMembers(formData.contractId);
    // 所需角色
    // 4 5 1 2 3
    const isCheck = hasRoleCode(projectTeam.value, [4, 5, 1, 3]);
    if (!isCheck) {
      NotifMessage.error("该合同未配置项目组成员，请先前往配置");
    } else {
      commitVisible.value = true;
      projectTeam.value.forEach(item => {
        if (item.roleCode === "5") {
          currentTeam.userName = item.userName;
          currentTeam.userId = item.userId;
        }
      });
    }
  } catch (err) {
    console.log(err);
  }
};

const handleRequest = async done => {
  try {
    // 后端要求，多次保存将传一个id过去
    const newFormData = Object.assign(formData, {
      id: +route.query?.contractId ?? ""
    });
    const newParams = {
      ...newFormData
    };

    const params = {
      formBaseInfo: newParams,
      formSubMap: {
        flowType: 5,
        assignee: currentTeam.userId, // 提交下一流程处理人Id
        opinion: `备注：${formData.remarks}`,
        isNeedRecord: "1",
        valueJson: JSON.stringify({
          selfCheckRecord: fieldEncode(
            "隐蔽自检记录",
            formData.selfCheckRecord
          ),
          flowStartAttachment: fieldEncode(
            "附件",
            formData.flowStartAttachmentArr
          )
        })
      }
    };
    const { code, message } = await postComFlowStart(params);
    if (code === 200) {
      // successMessage("到货验收发起成功");
      commitVisible.value = false;
      NotifMessage.success(message);
      // router.replace("/acceptance/concealed");
      handleBack();
    } else {
      // errorMessage(message);
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  } finally {
    setTimeout(() => {
      done();
    }, 1000);
  }
};

const getTeamMembers = async (id: string | number) => {
  try {
    const params = {
      id
    };
    const res: any = await getProTeamMembers(params);
    if (res.code === 200) {
      projectTeam.value = res.data.memberTypeList;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSave = async () => {
  formData.projectName = currentProject.projectName;
  formData.projectManageId = currentProject.projectManageId;
  formData.flowStartAttachmentArr = onFilterFileData(defaultFileList.value);
  // formData.billName = `${formData.projectName}-${formData.contractName}-有监理隐蔽验收`;

  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;

  // 后端要求，多次保存将传一个id过去
  const newFormData = Object.assign(formData, {
    id: +route.query?.contractId ?? ""
  });
  const params = {
    formBaseInfo: { ...newFormData },
    formSubMap: {
      flowType: 5,
      isNeedRecord: "1",
      valueJson: JSON.stringify({
        selfCheckRecord: formData.selfCheckRecord,
        flowStartAttachmentArr: formData.flowStartAttachmentArr
      })
    }
  };
  try {
    const { code, message, data } = await postFlowSave(params);
    if (code === 200) {
      const { fullPath, query } = unref(route);
      router.replace({
        path: "/redirect" + fullPath,
        query: Object.assign(query, { contractId: data.id })
      });
      // successMessage("到货验收发起成功");
      NotifMessage.success("保存成功");
      // router.replace("/acceptance/arrival");
    } else {
      // errorMessage(message);
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// 返回按钮事件
const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/acceptance/concealed", replace: true });
  }
};

getProjectList();
</script>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .form__content {
    flex: 1;
    width: inherit;
  }
  .form__footer {
    width: inherit;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// #tree-option
#tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}
// #tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
#tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
#default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

#default-option {
  padding: 0 10px;
}

.dialog__content {
  border: 1px solid #f0f4ff;
  border-radius: 4px;

  &--title {
    background: #f0f4ff;
    font-size: 16px;
    padding: 4px 8px;
  }
  .el-row {
    padding: 4px;
  }
  .col-left {
    text-align: right;
  }
  .col-right {
  }
}

:deep .el-select {
  width: 100%;
}
</style>
